/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.os.servlet;

import br.os.model.bean.Ordem;
import br.os.model.logic.OSModel;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

/**
 *
 * @author Rubean
 * Servlet responsável por efetuar baixa de ordens de serviços
 */
@WebServlet(name = "EfetuarBaixa", urlPatterns = {"/Baixar"})
public class EfetuarBaixa extends HttpServlet {

  private String message[] = {"Baixa Efetuada", "Baixa Nao Efetuada", "Problema na Solicitacao"};
  private String tecnico;
  private List<Ordem> ordens = new ArrayList<Ordem>();

  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    if (XMLtoConvert(request.getParameter("baixa"))) {
      writeResponse(response,OSModel.efetuarBaixaOS(tecnico, ordens) ? 0 :1);
    }else{
      writeResponse(response,2);
    }
  }

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP <code>GET</code> method.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Handles the HTTP <code>POST</code> method.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Returns a short description of the servlet.
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>

  public boolean XMLtoConvert(String xml) {
    if ((xml!=null) && (xml.length()>0)) {
      ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
      KXmlParser parser = new KXmlParser();
      try {
        parser.setInput(new InputStreamReader(bais));
        parser.nextTag();
        parser.require(XmlPullParser.START_TAG, null, "baixa");
        tecnico = parser.getAttributeValue(0);
        ordens  = new ArrayList<Ordem>();
        parser.nextTag();
        parser.require(XmlPullParser.START_TAG, null, "ordens");
        int qtde = Integer.parseInt(parser.getAttributeValue(0));
        parser.nextTag();
        for (int i = 0; i < qtde; i++) {
          parser.require(XmlPullParser.START_TAG, null,"ordem");
          Ordem ordem = new Ordem();
          ordem.setId(Integer.parseInt(parser.getAttributeValue(0)));
          ordem.setCliente(parser.getAttributeValue(1));
          ordem.setDtExecucao(new Date(Long.parseLong(parser.getAttributeValue(2))));
          ordem.setServico(parser.nextText());
          ordens.add(ordem);
          parser.require(XmlPullParser.END_TAG, null, "ordem");
          parser.nextTag();
        }
        parser.require(XmlPullParser.END_TAG, null, "ordens");
        parser.nextTag();
        parser.require(XmlPullParser.END_TAG, null, "baixa");
      } catch (XmlPullParserException ex) {
        Logger.getLogger(EfetuarBaixa.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException e) {
        Logger.getLogger(EfetuarBaixa.class.getName()).log(Level.SEVERE, null, e);
      }
    }

    return !(ordens.isEmpty());
  }
  /**
   * writeResponse
   */
  public void writeResponse(HttpServletResponse response, int code){
    try {
      response.setContentType("text/xml");
      PrintWriter out = response.getWriter();
      out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      out.println("<operacao id=\"2\">");
      out.println(String.format("<message code=\"%s\">%s</message>", String.valueOf(code), message[code]));
      out.println("</operacao>");
    } catch (IOException ex) {
      Logger.getLogger(EfetuarBaixa.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
   
}
